package com.beney.ds.sorting;

import com.beney.ds.sorting.abs.AbstractSort;

public class MergeSort extends AbstractSort {
    private MergeSort() {
    }

    public static void sort(Comparable[] arr) {
        if (arr == null) return;
        int len = arr.length;
        Comparable[] aux = new Comparable[len];
        sort(arr, aux, 0, len - 1);
    }

    private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
        if (lo >= hi) return;
        int mid = lo + (hi - lo) / 2;
        sort(a, aux, lo, mid);
        sort(a, aux, mid + 1, hi);
        merge(a, aux, lo, mid, hi);
    }

    /**
     * stably merge a[lo .. mid] with a[mid+1 .. hi] using aux[lo .. hi]
     */
    private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {
        if (hi + 1 - lo >= 0) // copy a[lo .. hi] to aux[lo .. hi]
            System.arraycopy(a, lo, aux, lo, hi + 1 - lo);
        int i = lo, j = mid + 1;
        for (int k = lo; k <= hi; ++k) {
            if      (i > mid)           a[k] = aux[j++];
            else if (j > hi)            a[k] = aux[i++];
            else if (isLess(aux, i, j)) a[k] = aux[i++];
            else                        a[k] = aux[j++];
        }
    }
}
